package cn.edu.niit.studyspace.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.litepal.crud.DataSupport;

import java.util.List;

import cn.edu.niit.studyspace.R;
import cn.edu.niit.studyspace.bean.User;

public class RegisterActivity extends AppCompatActivity {
    EditText etUsername;
    EditText etPassword;
    EditText etRepPassword;
    Button btnRegister;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        //初始化组件
        initComponent();
        //增加事件监听
        addAction();
    }

    private void initComponent() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        etRepPassword = findViewById(R.id.et_rep_password);
        btnRegister = findViewById(R.id.btn_regist);
    }

    private void addAction() {
        btnRegister.setOnClickListener(v -> register(v));
    }

    //注册
    public void register(View view) {
        String username = etUsername.getText().toString();
        String password = etPassword.getText().toString();
        String passwordRep = etRepPassword.getText().toString();
        if (username.isEmpty()) {
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        } else if (password.isEmpty() || passwordRep.isEmpty()) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        } else if (!password.equals(passwordRep)) {
            Toast.makeText(this, "两次密码不相同", Toast.LENGTH_SHORT).show();
            return;
        }
        List<User> result = DataSupport.select("id").where("username= '" + username+"'").find(User.class);
        if (result.size() > 0) {
            Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
            return;
        }
        User user = new User();
        user.setUsername(username);
        user.setNickname(username);
        user.setPassword(password);
        user.save();
        Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
        finish();
    }
}
